package com.smartfast4j.qiniu;

import com.qiniu.common.QiniuException;
import com.qiniu.util.StringUtils;
import com.smartfast4j.qiniu.bean.QiNiuUploadResult;
import com.smartfast4j.qiniu.util.FileUtil;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.util.List;
import java.util.Map;

/**
 * 基于七牛云存储的上传实现
 * Created by gacl on 2017/10/16.
 */
public class QiNiuFileService{

    private static Logger logger = Logger.getLogger(QiNiuFileService.class);

    /**
     * 文件上传后的存储方式
     */
    private static final String STORAGE_TYPE = "QiNiu";

    private QiNiuConfig qiNiuConfig;

    private QiNiuClient qiNiuClient;

    /**
     *
     *
     * 七牛客户端初始化用到的properties配置文件
     * @param configFilePath
     */
    public QiNiuFileService(String configFilePath){
        qiNiuClient = new QiNiuClient(configFilePath);
        qiNiuConfig = qiNiuClient.getQiNiuConfig();
    }

    public QiNiuUploadResult uploadFile(String filePath) {
        return uploadFile(filePath,"");
    }

    public QiNiuUploadResult uploadFile(String filePath, String savePath) {
        File file = new File(filePath);
        return uploadFile(file,savePath);
    }

    public QiNiuUploadResult uploadFile(InputStream inputStream, String fileName) {
        return uploadFile(inputStream,fileName,"");
    }

    public QiNiuUploadResult uploadFile(InputStream inputStream, String fileName, String savePath) {
        byte[] content = new byte[0];
        try {
            content = FileUtil.input2ByteArray(inputStream);
        } catch (IOException e) {
            logger.error(e.getMessage(),e);
        }
        return uploadFile2QiNiu(fileName, content, savePath);//七牛支持自定义存储路径
    }

    public QiNiuUploadResult uploadFile(File file, String savePath) {
       return uploadFile2QiNiu(file, savePath);
    }

    public QiNiuUploadResult uploadFile(byte[] fileByte, String fileName) {
       return uploadFile2QiNiu(fileName,fileByte);
    }

    public QiNiuUploadResult uploadFile(byte[] fileByte, String fileName, String savePath) {
        return uploadFile2QiNiu(fileName,fileByte, savePath);//七牛支持自定义存储路径
    }

    public QiNiuUploadResult uploadNetworkFile(String fileUrl) throws MalformedURLException {
        return uploadNetworkFile(fileUrl,"");
    }

    public QiNiuUploadResult uploadNetworkFile(String fileUrl, String fileExt) throws MalformedURLException {
        //下载网络文件
        byte[] content = FileUtil.downloadNetworkFile(fileUrl);
        String ext;
        if(!FileUtil.isEmpty(fileExt)){
            ext = fileExt;
        }else{
            ext = fileUrl.substring(fileUrl.lastIndexOf(".") + 1).toLowerCase();// 后缀名
        }
        logger.info("ext："+ext);
        String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1).toLowerCase()+"."+ext;
        return uploadFile(content,fileName);
    }

    /**
     * fileSavePath='1508746399255.jpg'
     * fileSavePath=gacl/test/1508748331013.jpg
     * @param fileSavePath
     * @return
     */
    public int deleteFile(String fileSavePath) {
        try {
            qiNiuClient.delete(fileSavePath);
        } catch (QiniuException e) {
            logger.error(e.getMessage(),e);
            return -1;
        }
        return 0;
    }

    /**
     * 批量删除
     * @param lstFileName
     * @return Map<String,Integer>
     */
    public Map<String,Integer> batchDeleteFile(List<String> lstFileName) {
        try {
            return qiNiuClient.batchDelete(lstFileName);
        } catch (QiniuException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 下载文件
     * @param fileUrl
     * @return
     */
    public byte[] downloadFile(String fileUrl) {
        try {
            //下载网络文件
            return  FileUtil.downloadNetworkFile(fileUrl);
        }catch (Exception e){
            return null;
        }
    }

    /**
     * 上传单个文件到七牛云存储，保存到指定目录下
     * @param fileName 要上传的文件
     * @param content 路径名称以/斜杠开头
     * @return
     */
    private QiNiuUploadResult uploadFile2QiNiu(String fileName, byte[] content, String savePath) {
        Long startTime = System.currentTimeMillis();
        QiNiuUploadResult uploadFile = new QiNiuUploadResult();
        //文件后缀名
        String ext = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();// 后缀名
        //使用时间戳生成新文件名
        String nFileName = System.currentTimeMillis() + "." + ext;
        uploadFile.setOriginalFileName(fileName);//上传文件的原始文件名
        uploadFile.setFileSuffix(ext);//文件扩展名
        uploadFile.setNewFileName(nFileName);//重命名后的文件名
        try {
            qiNiuClient.uploadFile(content, savePath + "/" + nFileName);
            String url;
            if(!StringUtils.isNullOrEmpty(savePath)){
                if(savePath.startsWith("/")){
                    url = qiNiuConfig.getServerDomain() + savePath + "/" + nFileName;
                }else{
                    url = qiNiuConfig.getServerDomain()+ "/" + savePath + "/" + nFileName;
                }
                uploadFile.setFileUrl(url);//文件URL地址
                uploadFile.setSavePath(savePath + "/" + nFileName);//文件保存路径
            }else{
                url = qiNiuConfig.getServerDomain()+ "/"+ nFileName;
                uploadFile.setFileUrl(url);//文件URL地址
                uploadFile.setSavePath("/" + nFileName);//文件保存路径
            }
            uploadFile.setStorageType(STORAGE_TYPE);//存放到七牛云存储
            uploadFile.setIsUploadSuccess(true);//上传成功
            logger.info("将文件上传到七牛云存储,上传的文件信息：" + uploadFile);
        } catch (Exception e) {
            logger.error("将文件上传到七牛云存储！", e);
            uploadFile.setIsUploadSuccess(false);//上传失败
        }
        Long endTime = System.currentTimeMillis();
        uploadFile.setUseTime(endTime-startTime);
        return uploadFile;
    }

    /**
     * 上传单个文件到七牛云存储，保存到指定目录下
     * @param fileName 要上传的文件
     * @param content 路径名称以/斜杠开头
     * @return
     */
    private QiNiuUploadResult uploadFile2QiNiu(String fileName, byte[] content) {
        return uploadFile2QiNiu(fileName, content, "");
    }

    /**
     * 上传单个文件到七牛云存储，保存到指定目录下
     * @return
     */
    private QiNiuUploadResult uploadFile2QiNiu(File file,String savePath) {
        Long startTime = System.currentTimeMillis();
        QiNiuUploadResult uploadFile = new QiNiuUploadResult();
        String fileName = file.getName();
        //文件后缀名
        String ext = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();// 后缀名
        //使用时间戳生成新文件名
        String nFileName = System.currentTimeMillis() + "." + ext;
        uploadFile.setOriginalFileName(fileName);//上传文件的原始文件名
        uploadFile.setFileSuffix(ext);//文件扩展名
        uploadFile.setNewFileName(nFileName);//重命名后的文件名
        try {
            qiNiuClient.uploadFile(file, savePath + "/" + nFileName);
            String url;
            if(!StringUtils.isNullOrEmpty(savePath)){
                if(savePath.startsWith("/")){
                    url = qiNiuConfig.getServerDomain() + savePath + "/" + nFileName;
                }else{
                    url = qiNiuConfig.getServerDomain()+ "/" + savePath + "/" + nFileName;
                }
                uploadFile.setFileUrl(url);//文件URL地址
                uploadFile.setSavePath(savePath + "/" + nFileName);//文件保存路径
            }else{
                url = qiNiuConfig.getServerDomain()+ "/"+ nFileName;
                uploadFile.setFileUrl(url);//文件URL地址
                uploadFile.setSavePath("/" + nFileName);//文件保存路径
            }
            uploadFile.setStorageType(STORAGE_TYPE);//存放到七牛云存储
            uploadFile.setIsUploadSuccess(true);//上传成功
            logger.info("将文件上传到七牛云存储,上传的文件信息：" + uploadFile);
        } catch (Exception e) {
            logger.error("将文件上传到七牛云存储！", e);
            uploadFile.setIsUploadSuccess(false);//上传失败
        }
        Long endTime = System.currentTimeMillis();
        uploadFile.setUseTime(endTime-startTime);
        return uploadFile;
    }

    /**
     * 上传单个文件到七牛云存储，保存到指定目录下
     * @return
     */
    private QiNiuUploadResult uploadFile2QiNiu(File file) {
        return uploadFile2QiNiu(file,"");
    }
}
